/**
 * @description 处理订单信息
 * @author 李哲
 */
const Order = require('../model/Order');
const Address = require('../model/Address');
const Product = require('../model/Product');

/**
 * 
 * @param {string} username 用户姓名
 * @param {Object} data 前端传入的数据
 * @returns 
 */
const createOrder = async (username, data) => {
    const {
        addressId,
        shopId,
        shopName,
        isCanceled = false,
        products = [] } = data
    const address = Address.findById(addressId);
    const pIds = products.map(item => item.id);
    const productList = await Product.find({
        shopId,
        _id: {
            $in: pIds
        }
    })
    const productListWidthSales = productList.map(p => {
        const id = p._id.toString();
        const filterProducts = products.filter(item => item.id === id)
        if (filterProducts.length === 0) {
            throw Error('未找到匹配项')
        }
        return {
            product: p,
            orderSales: filterProducts[0].num
        }
    })
    const newOrder = await Order.create({
        username,
        shopId,
        shopName,
        isCanceled,
        address,
        products: productListWidthSales
    })
    return newOrder
}
/**
 * 获取订单列表
 * @param {String} username 用户姓名
 * @returns 
 */
const getOrderList = async (username) => {
    const newOrder = await Order.find({ username }).sort({ _id: -1 })
    return newOrder
}
module.exports = { createOrder, getOrderList }